package com.northpool.operator.dataset.statistics;

import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.common.database.DatabaseUtils;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;
import com.northpool.resources.datasource.IDataSource;
import com.northpool.resources.datatable.bean.TableMetaStatistics;
import com.northpool.resources.datatable.operate.ITableOperator;

@OperatorInfo(
        ref = "TableDiskSizeOperator",
        version = "0.0.1",
        name = "表磁盘大小",
        description = "统计数据表占用的磁盘大小"
)
@OutputParams({
        @OutputParam(ref = "size", name = "磁盘大小", desc = "占用磁盘大小，字节数"),
        @OutputParam(ref = "sizeMB", name = "磁盘大小MB", desc = "占用磁盘大小，字节数")
})
public class TableDiskSizeOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "datasource", name = "数据源", desc = "数据源ID"),
            @InputParam(ref = "tableName", name = "表名称", desc = "数据表名称，如: public.tb_test"),
    })
    public TableDiskSizeOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(TableDiskSizeOperator.class,
                TestParamBuilder.aBuilder()
                        .param("datasource", "test_bcg")
                        .param("tableName", "dltb_building_b_all")
                        .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String datasource = paramTool.getStr("datasource");
        String dataSourceJson = DatabaseUtils.getDataSourceJson(datasource);
        String tableName = paramTool.getStr("tableName");
        IDataSource ds = IDataSource.fromJSON(dataSourceJson);
        ITableOperator tableOperator = ds.getTableOperator(tableName);
        TableMetaStatistics metaStatistics = tableOperator.getMetaStatistics(false);
        long diskSpaceSize = metaStatistics.getDiskSpaceSize();
        this.result("size", diskSpaceSize);
        this.result("sizeMB", diskSpaceSize / 1024.0 / 1024.0);
    }
}
